package com.mimaxueyuan.disruptor.demo3;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;

/**
 * @author: Kevin
 * @官网: 	www.mimaxueyuan.com
 * @Q Q群:	660567408
 * @Email:	mimaxueyuan@163.com
 * [每天进步一点点、人生带来大改变...]
 * [本代码对应视频地址:http://study.163.com/course/introduction/1004573050.htm]
 */
public class UserEventMain1 {

	public static long startTime;
	
	@SuppressWarnings("unchecked")
	public static void main(String[] args) throws InterruptedException {
		ThreadFactory threadFactory = Executors.defaultThreadFactory();
		UserEventFactory factory = new UserEventFactory();
		int bufferSize = 1024;
		Disruptor<UserEvent> disruptor = new Disruptor<UserEvent>(factory, bufferSize, threadFactory);
		
		UserEventHandler1 userEventHandler1 = new UserEventHandler1();
		UserEventHandler2 userEventHandler2 = new UserEventHandler2();
		
		//指定两个消费者(并行)
		disruptor.handleEventsWith(userEventHandler1);
		disruptor.handleEventsWith(userEventHandler2);
		
		//设置默认的ExceptionHandler
		disruptor.setDefaultExceptionHandler(new DefaultUserEventExceptionHandler());
		//为userEventHandler1指定异常处理类为UserEventExceptionHandler1
		disruptor.handleExceptionsFor(userEventHandler1).with(new UserEventExceptionHandler1());
		//为userEventHandler2指定异常处理类为UserEventExceptionHandler2
		disruptor.handleExceptionsFor(userEventHandler2).with(new UserEventExceptionHandler2());
		
		disruptor.start();
		
		RingBuffer<UserEvent> ringBuffer = disruptor.getRingBuffer();
		final UserEventProducerWithTranslator translator = new UserEventProducerWithTranslator(ringBuffer);
		
		//5线程并发下的Disruptor
		ExecutorService executor1 = Executors.newCachedThreadPool();
		startTime = System.currentTimeMillis();
		for (int i = 0; i<5; i++) {
			final int id = i;
			executor1.submit(new Runnable() {
				public void run() {
					try {
						User user = new User();
						user.setId(id);
						user.setName("kevin"+id);
						user.setAge(id+10);
						user.setAddress("beijing"+id);
						translator.onData(user);
					}catch(Exception e) {
						e.printStackTrace();
					}
				}
			});
		}
		
	}

}
